package org.jupiter.blog.api.annotation;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.lang.reflect.Field;

public class NotEqualFieldsValidator implements ConstraintValidator<NotEqualFields, Object> {

	private String sourceField;

	private String targetField;

	private String message;

	@Override
	public void initialize(NotEqualFields constraintAnnotation) {
		this.sourceField = constraintAnnotation.sourceField();
		this.targetField = constraintAnnotation.targetField();
		this.message = constraintAnnotation.message();
	}

	@Override
	public boolean isValid(Object value, ConstraintValidatorContext context) {
		if (value == null)
			return true;

		try{
			Field f1 = value.getClass().getDeclaredField(sourceField);
			Field f2 = value.getClass().getDeclaredField(targetField);
			f1.setAccessible(true);
			f2.setAccessible(true);

			Object val1 = f1.get(value);
			Object val2 = f2.get(value);

			if (val1 == null || val2 == null)
				return true;

			boolean valid = !val1.equals(val2);

			if (!valid){
				context.disableDefaultConstraintViolation();
				context.buildConstraintViolationWithTemplate(message)
						.addPropertyNode(targetField)
						.addConstraintViolation();
			}

			return valid;

		} catch (NoSuchFieldException | IllegalAccessException e){
			e.printStackTrace();
			return true;
		}
	}
}
